<?php

class UsersController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }
    
    public function registerAction()
    {
    	$user = new Application_Model_Users();
    	$form = $user->getForm(0);
    	$this->view->form = $form;
    	$this->view->title = 'Регистрация нового пользователя';
    	if($this->_request->isPost())
        {
        	if ($form->isValid( $this->_getAllParams() )) 
        	{
        		if ( $this->_getParam('Password') == $this->_getParam('PassConfirm') )
        		{
        			$Data = $form->getValues();
        			$user->addUser($Data);
        			echo "<br /><br />	<span style='color:green; font-weight:bold;'>
        			Ожидайте подтверждение вашей учетной записи от администратора!
        			</span>";
					$form->clearElements();        		
        		} 
        		else 
        		{
        			echo "Повторный пароль введен неверно!";
        		}
			}
				
	
        }
        
    }
    
	public function saveProfileAction()
    {
    	$this->_helper->layout()->disableLayout();
    	$this->_helper->viewRenderer->setNoRender();
    	$user = new Application_Model_Users();
    	$data = $this->_getAllParams();
    	$id = $user->getCurrentUser()->id;
    	$data['id'] = $id;
    	$user->editUser( $data );
        $this->_redirect('');
    }
    
    public function getProfileAction()
    {
    	$this->_helper->layout()->disableLayout();
    	$this->_helper->viewRenderer->setNoRender();
    	$user = new Application_Model_Users();
    	$id = $user->getCurrentUser()->id;
    	$currentUser = $user->getOneUser( $id ); 
    	echo Zend_Json::encode($currentUser);
    }
    
 	public function setPasswordAction()
    {
 
    	$this->_helper->layout()->disableLayout();
    	$this->_helper->viewRenderer->setNoRender();
    	$user = new Application_Model_Users();
    	$data = $this->_getAllParams();
    	$id = $user->getCurrentUser()->id;
    	$data['id'] = $id;
    	if ( $data['Password'] == $data['PassConfirm'] && strlen( $data['Password']) >= 6)
    	{
    		echo Zend_Json::encode('Пароль успешно изменен!');
    		$user->setPassword( $data );
    	}else 
    	{
    		echo Zend_Json::encode('Пароль не изменен! Проверьте правильность ввода! Пароль должен содержать не менее 6 символов! ');
    	}
        //$this->_redirect('');
    }
    
	public function editAction()
    {
    	$Users = new Application_Model_Users();
    	$Data = $Users->getOneUser($this->_request->getParams('id',0));
    	$form = $Users->getForm(1, $Data );
    	$this->view->title = 'Редактирование профиля';
    	$this->view->form = $form;
    	if($this->_request->isPost())
        {
        	if ($form->isValid( $this->_getAllParams() )) 
        	{
        		if ( $this->_getParam('Password') == $this->_getParam('PassConfirm') )
        		{
        			$Data = $form->getValues();
        			$Data['id'] = $this->_request->getParam('id',0);
        			$Users->editUser($Data);
        		} 
        		else 
        		{
        			echo "Повторный пароль введен неверно!";
        		}
			}
        }
    }

    public function indexAction()
    {
    	$this->view->title = 'Пользователи';

        $usersDAO = new Application_Model_Users();
        $this->view->users = $usersDAO->getAllUsers();
    }
    
  	public function deleteAction()
    {
//    	sleep(5);
    	$this->_helper->layout()->disableLayout();
    	$this->_helper->viewRenderer->setNoRender();
    	$User = new Application_Model_Users();
		$items = $this->_getAllParams();
		$itemIds = $items['ids'];
		foreach ( $itemIds as $k => $v )
		{
			$User->Remove($v);
		}
		
		echo Zend_Json::encode(array('status'=>0,'message'=>"Операция успешно завершена")); 
		
		//$this->_redirect('users');
    }
    
    public function addAction()
    {
    	$User = new Application_Model_Users();
    	$form = $User->getForm(0,array());
    	$Data = array();
    	$this->view->form = $form;
    	$this->view->title = 'Добавление нового пользователя';
    	if($this->_request->isPost())
        {
        	if ($form->isValid( $this->_getAllParams() )) 
        	{
        		if ( $this->_getParam('Password') == $this->_getParam('PassConfirm') )
        		{
        			$Data = $form->getValues();
        			$User->addUser($Data);
        		} 
        		else 
        		{
        			echo "Повторный пароль введен неверно!";
        		}
			}
        }
    }

    public function loginAction()
    {
   		 $this->view->message = '';
   		 $this->view->title = 'Аутентификация нового пользователя';

        if ($this->_request->isPost()) {
            $f = new Zend_Filter_StripTags();
            $username = $f->filter($this->_request->getPost('username'));
            $password = $f->filter($this->_request->
            getPost('password'));

            if (empty($username)) {
                $this->view->message = 'Введите имя пользователя!';
            } else {
                // setup Zend_Auth adapter for a database table
                $dbAdapter  = Zend_Registry::get('dbAdapter');
                
                $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
                
                $authAdapter->setTableName('users');
                $authAdapter->setIdentityColumn('Login');
                $authAdapter->setCredentialColumn('Password');

                // Set the input credential values 
                // to authenticate against
                $authAdapter->setIdentity($username);
                $authAdapter->setCredential($password);

                // do the authentication
                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapter);
                if ($result->isValid()) {
                    // success: store database row to auth's storage
                    // system. (Not the password though!)
                    $data = $authAdapter->getResultRowObject(null, 'Password');
                    $auth->getStorage()->write($data);
			        $this->_redirect('files');
                } else {
                    // failure: clear database row from session
                    $this->view->message = 'Аутентификация прошла не успешно!';
                }
            }
        }
    }

    public function logoutAction()
    {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect('');
    }
    
	public function setApprovedAction()
    {
    	$this->_helper->layout()->disableLayout();
    	$this->_helper->viewRenderer->setNoRender();
    	$newValue = $this->_getParam('value');
    	$id = $this->_getParam('id');
    	$User = new Application_Model_Users();
    	$User->setApprove($id,$newValue);
    	echo Zend_Json::encode("Статус успешно изменен!");
    }
    
	public function setBannAction()
    {
    	$this->_helper->layout()->disableLayout();
    	$this->_helper->viewRenderer->setNoRender();
    	$newValue = $this->_getParam('value');
    	$id = $this->_getParam('id');
    	$User = new Application_Model_Users();
    	$User->setBan($id,$newValue);
    	echo Zend_Json::encode("Статус успешно изменен!");
    }

}





